package com.quick.android.handler.image;

import java.io.File;

import com.nostra13.universalimageloader.cache.disc.DiskCache;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.download.ImageDownloader.Scheme;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;
import com.quick.android.app.AppConfig;
import com.quick.android.utils.CheckUtils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;

public class ImageLoadHandler {
	private static ImageLoadHandler mInstance;
	public static int memoryCacheSize = 8 * 1024 * 1024;
	public static int diskCacheSize = 50 * 1024 * 1024;
	/**
	 * 是否可以加载图片<br>
	 * 当没有加载存储卡时，默认不加载图片，只显示默认图
	 * */
	public static boolean isCanLoad = true;
	private Context mContext;
	private ImageLoader mImageLoader;
	private DisplayImageOptions mDefaultOptions;
	private DisplayImageOptions mLargerOptions;

	public static ImageLoadHandler getInstance(Context context) {
		if (mInstance == null) {
			mInstance = new ImageLoadHandler(context);
		}
		return mInstance;
	}

	private ImageLoadHandler(Context context) {
		mContext = context;
		mImageLoader = ImageLoader.getInstance();
		initImageLoader(mContext);
	}

	private void initImageLoader(Context context) {
		if (!Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			isCanLoad = false;
		}
		ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
				context).threadPriority(Thread.NORM_PRIORITY - 2)
				.threadPoolSize(5)
				.denyCacheImageMultipleSizesInMemory()
				.memoryCache(new WeakMemoryCache()) 
				.diskCacheFileNameGenerator(new Md5FileNameGenerator())
				.memoryCacheSize(memoryCacheSize).diskCacheSize(diskCacheSize)
				.tasksProcessingOrder(QueueProcessingType.LIFO);

		if (isCanLoad) {
			File cacheDir = new File(context.getExternalCacheDir(), "images");
			builder.diskCache(new UnlimitedDiscCache(cacheDir));
		}
		if (AppConfig.isDebug) {
			builder.writeDebugLogs();
		}
		ImageLoaderConfiguration config = builder.build();
		mImageLoader.init(config);
	}

	/** 在内存不够用时，可以清除缓存，减小APP内存压力 */
	public void clearCache() {
		mImageLoader.clearMemoryCache();
	}
	
	/** 加载普通图片的Options设置 */
	private void setOptions(int imgLoadingRes) {
		mDefaultOptions = new DisplayImageOptions.Builder()
				.showImageOnLoading(imgLoadingRes)
				.showImageForEmptyUri(imgLoadingRes)
				.showImageOnFail(imgLoadingRes).cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true).build();
	}

	/** 加载大图的Options设置 */
	private void setLargerOptions(int imgLoadingRes) {
		mLargerOptions = new DisplayImageOptions.Builder()
				.showImageOnLoading(imgLoadingRes)
				.showImageForEmptyUri(imgLoadingRes)
				.showImageOnFail(imgLoadingRes).cacheInMemory(true)
				.cacheOnDisk(true).considerExifParams(true).build();
	}

	/** 读取本地文件名 */
	public String getFileUri(String imagePath) {
		return Scheme.FILE.wrap(imagePath);
	}

	/** 读取Assets文件名 */
	public String getAssetsUri(String imagePath) {
		return Scheme.ASSETS.wrap(imagePath);
	}

	/** 读取Drawable资源id文件名 */
	public String gtetDrawableUri(String drawableName) {
		return Scheme.DRAWABLE.wrap(drawableName);
	}

	/**
	 * 加载正常图片
	 * 
	 * @param mImageView
	 * @param url
	 * @param width
	 * @param height
	 */
	public void loadDefaultImage(final ImageView mImageView, final String url,
			int width, int height) {
		loadImage(mImageView, url, width, height, mDefaultOptions);
	}

	/**
	 * 加载大图（例如Banner）
	 * 
	 * @param mImageView
	 * @param url
	 * @param width
	 * @param height
	 */
	public void loadLargerImage(final ImageView mImageView, final String url,
			int width, int height) {
		loadImage(mImageView, url, width, height, mLargerOptions);
	}

	/**
	 * 加载正常图片
	 * 
	 * @param mImageView
	 * @param url
	 * @param width
	 * @param height
	 */
	public void loadImage(final ImageView mImageView, final String url,
			int width, int height, DisplayImageOptions option) {
		if (mImageView == null || CheckUtils.isStrEmpty(url)) {
			return;
		}
		final Drawable loadingDrawable = option.getImageOnLoading(mContext
				.getResources());
		if (!isCanLoad) {
			mImageView.setImageDrawable(loadingDrawable);
			return;
		}

		mImageView.setTag(url);
		ImageSize size = new ImageSize(width, height);
		mImageLoader.loadImage(url, size, option, new ImageLoadingListener() {

			@Override
			public void onLoadingCancelled(String arg0, View arg1) {
				mImageView.setImageDrawable(loadingDrawable);
			}

			@Override
			public void onLoadingComplete(String arg0, View arg1, Bitmap bitmap) {
				mImageView.setImageBitmap(bitmap);
			}

			@Override
			public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
				mImageView.setImageDrawable(loadingDrawable);
			}

			@Override
			public void onLoadingStarted(String arg0, View arg1) {
				mImageView.setImageDrawable(loadingDrawable);
			}
		});
	}

	/** 优化ListView滑动时加载图片问题 */
	public void optimizationListView(ListView listView, boolean pauseOnScroll,
			boolean pauseOnFling) {
		listView.setOnScrollListener(new PauseOnScrollListener(mImageLoader,
				pauseOnScroll, pauseOnFling));
	}

	/** 优化GridView滑动时加载图片问题 */
	public void optimizationGridView(GridView gridView, boolean pauseOnScroll,
			boolean pauseOnFling) {
		gridView.setOnScrollListener(new PauseOnScrollListener(mImageLoader,
				pauseOnScroll, pauseOnFling));

	}

}
